<?php
/* SVN FILE: $Id: p_r_g_controller.php 107 2007-04-14 17:07:09Z Andy $ */

/**
 * Short description for file.php.
 *
 * Long description for file
 *
 * PHP versions 4 and 5
 *
 * Copyright (c), Andy Dawson
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @filesource
 * @copyright    Copyright (c) 2007, Andy Dawson
 * @package      noswad
 * @subpackage   noswad.app.plugins.pagination.controllers
 * @since        Noswad site version 3
 * @todo         TODO Edit this block
 * @version      $Revision: 107 $
 * @created      26/01/2007
 * @modifiedby   $LastChangedBy$
 * @lastmodified $Date: 2007-04-14 19:07:09 +0200 (sáb, 14 abr 2007) $
 * @license      http://www.opensource.org/licenses/mit-license.php The MIT License
 */

/**
 * Short description for Class
 *
 * Long descrption of Class
 */

/**
 * Description for var
 *
 * @var type
 * @access public/private/protected
 */

/**
 * Description for method
 *
 * @param type $name description
 * @return type description
 */
 class PRGController extends PaginationAppController {
	var $name = 'PRG'; // required for PHP4 installs

	function index() {
		if ($this->data['Form']['search']) {
			$match = $this->data['Form']['search'];
			uses('Sanitize');
			$this->set('url',$this->webroot.$this->plugin.'/'.$this->name.'/results/'.Sanitize::paranoid($match));
			$this->layout = 'redirect';
			$this->render('redirect');
			$this->_addFlash('This is step 3, the url now contains the search term, or any other info required as decided by the developer, and so there is no form data to be lost.');
		}
	}

	function results($match = null) {
		uses('Sanitize');
		$match = Sanitize::paranoid($match);
		if (!$match) {
			return $this->redirect (array('action'=>'index'));
		}
		$this->_addFlash('Showing results for Titles matching "'.$match.'"');
		$criteria = array('Title.title'=>"like %$match%");
		list($order,$limit,$page) = $this->Pagination->init($criteria,null,array('ajaxAutoDetect'=>false));
		$this->data = $this->{$this->modelClass}->findAll($criteria, null, $order, $limit, $page);
		$this->viewPath = 'normal';
		$this->render('index');
	}

	function in_one($match = null) {
		uses('Sanitize');
		if (isset($this->data['Form']['search'])) {
			if (!$this->data['Form']['search']) {
				$this->_addFlash('You need to search for something');
			}
			return $this->redirect (array(Sanitize::paranoid($this->data['Form']['search'])));
		}
		if ($match) {
			$match = Sanitize::paranoid($match);
			$this->_addFlash('Showing results for Titles matching "'.$match.'"');
			$criteria = array('Title.title'=>"LIKE %$match%");
			list($order,$limit,$page) = $this->Pagination->init($criteria,null,array('ajaxAutoDetect'=>false));
			$this->data = $this->{$this->modelClass}->findAll($criteria, null, $order, $limit, $page);
			$this->data['Form']['search'] = $match;
		} else {
			$this->data = null;
		}
		$this->render('in_one');
	}

	function complex() {
		$this->_defineSelects();
		if ($this->data) {
			$URL = $this->_generateURL($this->data);
			return $this->redirect(array($URL));
		}
		$args = $this->_searchParse();
		list($criteria,$Display) = $this->_generateConstraint($args);
		if($Display) {
			$this->_addFlash('Showing results for Titles matching: '.implode(', ',$Display).'.');
		} else {
			$this->_addFlash('Currently showing all results.');
		}
		list($order,$limit,$page) = $this->Pagination->init($criteria);
		$results = $this->{$this->modelClass}->findAll($criteria, null, $order, $limit, $page);
		$this->set('results',$results);
		$this->render('complex');
	}

	function ajaxed () {
		$this->_defineSelects();
		if (($this->data)&&(!isset($this->params['requested']))) {
			$URL = $this->_generateURL($this->data);
			return $this->redirect(array($URL));
		}
		$args = $this->_searchParse();
		list($criteria,$Display) = $this->_generateConstraint($args);
		if($Display) {
			$this->_addFlash('Showing results for Titles matching: '.implode(', ',$Display).'.');
		} else {
			$this->_addFlash('Currently showing all results.');
		}
		list($order,$limit,$page) = $this->Pagination->init($criteria);
		$results = $this->{$this->modelClass}->findAll($criteria, null, $order, $limit, $page);
		$this->set('results',$results);
		$this->set('ajaxed',$this->RequestHandler->isAjax());
		$this->render('ajaxed');
	}

	function _generateURL($data) {
		$URL = '';
		foreach ($data as $model => $array1) {
			$model = Inflector::camelize($model);
			foreach($array1 as $field => $value) {
				$value = preg_replace('#\W+#i', '', $value);
				//$this->log("$field = '". ord($value).''');
				//print_r(var_dump(urlencode($value)));
				if(strlen(trim($value)) > 0 ) {
				//if ($value) {
		            if(strpos($field, '-')) {
		                list($field, $operator) = split('-', $field);
		            } else {
		            	$operator = '';
		            }
					$field = Inflector::camelize($field);
					if ($model == $this->modelClass) {
						$URL .= $field.':';
					} else {
						$URL .= $model.'-'.$field.':';
					}
					if ($operator) {
						$URL .= $operator.'-';
					}
					$URL .= $value.'/';
				}
			}
		}
		return $URL;
	}

	function _searchParse () {
		$args = $this->passedArgs;
		$c = count($args);
		if (is_array($args)) {
			foreach ($args as $arg) {
	            if(strpos($arg, ':')) {
	                list($field, $value) = split(':', $arg);
		            if(strpos($field, '-')) {
		                list($model, $field) = split('-', $field);
		            } else {
		            	$model = 'Title';
		            }
		            if(strpos($value, '-')) {
		                list($operator, $value) = split('-', $value);
						//$operator = $this->_convertComparison($operator);
		            } else {
		            	$operator = '=';
		            }
					$a[$model][$field][$operator] = $value;
	            }
			}
		return $a;
		} else {
			return array();
		}
	}

  function _generateConstraint($Inputs=null) {
	uses('inflector');
	$restructured = array();
  	$Constraint = array();
	$Display = array();
	$data = array();
	foreach ($Inputs as $modelName=>$array1) {
		$modelName = Inflector::camelize($modelName);
		foreach ($array1 as $field => $array2) {
			$field = Inflector::underscore($field);
			foreach ($array2 as $operatorStr =>$value) {
				if ($modelName == $this->modelClass) {
					$Dis = Inflector::Humanize($field).' ';
				} else {
					$Dis = Inflector::Humanize($modelName).' '.Inflector::Humanize($field).' ';
				}
				if ($operatorStr=='cont') {
					$Constraint[$modelName.'.'.$field] = 'LIKE %'.$value.'%';
					$Dis .= 'contains ';
					$data[$modelName][low($field.'-'.$operatorStr)] = $value;
				} elseif ($operatorStr<>'=') {
					$operator = $this->_convertComparison($operatorStr);
					$Constraint[$modelName.'.'.$field] = $operator.' '.$value;
					$Dis .= $operatorStr.' ';
					$data[$modelName][low($field.'-'.$operatorStr)] = $value;
				} else {
					$Constraint[$modelName.'.'.$field] = $value;
					$Dis .= ' is ';
					$data[$modelName][low($field)] = $value;
				}
				$Dis .= $value;
				$Display[] = $Dis;
			}
		}
	}
	$this->data= $data;
	$Constraint=$Constraint?$Constraint:null;
	$Display=$Display?$Display:null;
	return array($Constraint,$Display);
	}

	function _convertComparison ($text='=') {
		switch ($text) {
			case 'gte':
				return '>=';
			case 'gt':
				return '>';
			case 'lte':
				return '<=';
			case 'lt':
				return '<';
			default:
				return '=';
		}
	}

	function _defineSelects () {
		$this->set('cats', $this->Title->Category->generatelist());
		$this->set('pubs', $this->Title->Publisher->generatelist());
		$this->set('selected_cats', array());
		$this->set('selected_pubs', array());
	}

	function _defineContextMenus() {
		return array (
			'Actions' => array (
				'data' => array (
					array (
						'title' => '3 step',
						'url' => "/{$this->plugin}/PRG/"
					),
					array (
						'title' => '1 step',
						'url' => "/{$this->plugin}/PRG/in_one"
					),
					array (
						'title' => 'Complex',
						'url' => "/{$this->plugin}/PRG/complex"
					)
				)
			)
		);
	}
}
?>